/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.order.controller;

import cn.denvie.springcloud.api.service.HelloService;
import cn.denvie.springcloud.order.domain.dto.OrderDTO;
import cn.denvie.springcloud.order.domain.dto.UserDTO;
import cn.denvie.springcloud.order.rpc.feign.UserFeignDubboService;
import cn.denvie.springcloud.order.rpc.feign.UserFeignService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * OrderController。
 *
 * @author Denvie
 * @date 2022/3/29
 * @since 1.0.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private UserFeignDubboService userFeignDubboService;
    @DubboReference
    private HelloService helloService;

    /**
     * 查询订单详情。
     */
    @GetMapping("/{id}")
    public OrderDTO query(@PathVariable Long id) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(id);
        orderDTO.setAmount(BigDecimal.valueOf(ThreadLocalRandom.current().nextInt()));
        orderDTO.setComment("comment " + ThreadLocalRandom.current().nextInt());

        // 通过 Feign 调用从用户中心查询用户信息
        orderDTO.setUserDTO(userFeignService.query(ThreadLocalRandom.current().nextLong()));

        return orderDTO;
    }

    /**
     * 查询用户订单列表。
     */
    @GetMapping("/listAll/{userId}")
    public List<OrderDTO> listAll(@PathVariable Long userId) {
        List<OrderDTO> resultList = new ArrayList<>();
        OrderDTO orderDTO;
        UserDTO userDTO;
        for (int i = 0; i < 5; i++) {
            orderDTO = new OrderDTO();
            orderDTO.setId((long) i);
            orderDTO.setAmount(BigDecimal.valueOf(ThreadLocalRandom.current().nextInt()));
            orderDTO.setComment("comment " + ThreadLocalRandom.current().nextInt());

            String url = String.format("http://user-center/user/%d", userId);
            userDTO = restTemplate.getForObject(url, UserDTO.class);
            orderDTO.setUserDTO(userDTO);

            resultList.add(orderDTO);
        }
        return resultList;
    }

    /**
     * 查询所有用户列表。
     */
    @GetMapping("/listUsers")
    public List<UserDTO> listUsers() {
        return userFeignService.list();
    }

    @GetMapping("/hello")
    public String hello(@RequestParam String name) {
        // 使用 userFeignDubboService.hello(name);
        if (name.length() % 2 == 0) {
            return userFeignDubboService.hello(name);
        }
        return helloService.hello(name);
    }
}
